import { useState, useRef, useEffect, forwardRef, useImperativeHandle } from "react";

export const ContextAudio = forwardRef<{ destroy: () => void }, { onDestroy?: () => void }>(({ onDestroy }, ref) => {
  const [isPlaying, setIsPlaying] = useState(false);
  const [volume, setVolume] = useState(0.5);
  const [isLoop, setIsLoop] = useState(true);
  const [duration, setDuration] = useState(0);
  const [currentTime, setCurrentTime] = useState(0);
  
  const audioContextRef = useRef<AudioContext | null>(null);
  const audioBufferRef = useRef<AudioBuffer | null>(null);
  const sourceNodeRef = useRef<AudioBufferSourceNode | null>(null);
  const gainNodeRef = useRef<GainNode | null>(null);
  const startTimeRef = useRef<number>(0);
  const pauseTimeRef = useRef<number>(0);

  useImperativeHandle(ref, () => ({
    destroy: () => {
      if (sourceNodeRef.current) {
        console.log('🧹 手动销毁Web Audio实例');
        sourceNodeRef.current.stop();
        sourceNodeRef.current.disconnect();
      }
      if (gainNodeRef.current) {
        gainNodeRef.current.disconnect();
      }
      if (audioContextRef.current) {
        audioContextRef.current.close();
      }
      onDestroy?.();
    }
  }));

  useEffect(() => {
    console.log('🔧 初始化AudioContext');
    
    // 检测iOS设备
    const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent);
    const iosVersionMatch = navigator.userAgent.match(/OS (\d+)_(\d+)_?(\d+)?/);
    const iosVersion = iosVersionMatch ? `${iosVersionMatch[1]}.${iosVersionMatch[2]}${iosVersionMatch[3] ? '.' + iosVersionMatch[3] : ''}` : null;
    console.log('📱 设备检测 - iOS:', isIOS);
    console.log('📱 iOS版本:', iosVersion || '未知');
    console.log('📱 User Agent:', navigator.userAgent);
    console.log('📱 Web Audio支持:', typeof AudioContext !== 'undefined' || typeof (window as unknown as {webkitAudioContext?: unknown}).webkitAudioContext !== 'undefined');
    
    // 创建AudioContext
    const AudioContextClass = window.AudioContext || (window as unknown as {webkitAudioContext?: typeof AudioContext}).webkitAudioContext;
    if (AudioContextClass) {
      audioContextRef.current = new AudioContextClass();
      console.log('🎵 AudioContext创建成功，状态:', audioContextRef.current.state);
      
      // 创建GainNode用于音量控制
      gainNodeRef.current = audioContextRef.current.createGain();
      gainNodeRef.current.connect(audioContextRef.current.destination);
      gainNodeRef.current.gain.value = volume;
      
      // 加载音频文件
      loadAudio();
    } else {
      console.error('❌ 浏览器不支持Web Audio API');
      alert('您的浏览器不支持Web Audio API');
    }

    return () => {
      if (sourceNodeRef.current) {
        sourceNodeRef.current.stop();
        sourceNodeRef.current.disconnect();
      }
      if (gainNodeRef.current) {
        gainNodeRef.current.disconnect();
      }
      if (audioContextRef.current) {
        audioContextRef.current.close();
      }
      onDestroy?.();
    };
  }, []);

  const loadAudio = async () => {
    try {
      console.log('📥 开始加载音频文件');
      const response = await fetch('https://creation.codemao.cn/884/l31cw9bi.mpeg');
      const arrayBuffer = await response.arrayBuffer();
      const audioBuffer = await audioContextRef.current!.decodeAudioData(arrayBuffer);
      audioBufferRef.current = audioBuffer;
      setDuration(audioBuffer.duration);
      console.log('✅ 音频加载完成，时长:', audioBuffer.duration.toFixed(2) + 's');
    } catch (error) {
      console.error('❌ 音频加载失败:', error);
      alert('音频文件加载失败，请检查网络连接');
    }
  };

  useEffect(() => {
    if (gainNodeRef.current) {
      gainNodeRef.current.gain.value = volume;
    }
  }, [volume]);

  const createSourceNode = () => {
    if (!audioContextRef.current || !audioBufferRef.current) return null;
    
    const sourceNode = audioContextRef.current.createBufferSource();
    sourceNode.buffer = audioBufferRef.current;
    sourceNode.loop = isLoop;
    sourceNode.connect(gainNodeRef.current!);
    
    // 添加事件监听
    sourceNode.onended = () => {
      console.log('🏁 音频播放结束');
      setIsPlaying(false);
      setCurrentTime(0);
    };
    
    return sourceNode;
  };

  const togglePlay = async () => {
    if (!audioContextRef.current || !audioBufferRef.current) {
      console.log('❌ AudioContext或音频缓冲区不存在');
      return;
    }

    // 如果AudioContext被暂停，需要恢复
    if (audioContextRef.current.state === 'suspended') {
      await audioContextRef.current.resume();
      console.log('🎵 AudioContext已恢复');
    }

    if (isPlaying) {
      console.log('⏸️ 执行暂停操作');
      if (sourceNodeRef.current) {
        sourceNodeRef.current.stop();
        sourceNodeRef.current.disconnect();
        pauseTimeRef.current = audioContextRef.current.currentTime - startTimeRef.current;
        sourceNodeRef.current = null;
      }
      setIsPlaying(false);
    } else {
      console.log('▶️ 执行播放操作');
      
      // 创建新的源节点
      const sourceNode = createSourceNode();
      if (!sourceNode) return;
      
      sourceNodeRef.current = sourceNode;
      
      // 计算开始时间
      const startOffset = pauseTimeRef.current;
      startTimeRef.current = audioContextRef.current.currentTime - startOffset;
      
      sourceNode.start(0, startOffset);
      setIsPlaying(true);
      
      // 开始时间更新
      startTimeUpdate();
    }
  };

  const startTimeUpdate = () => {
    const updateTime = () => {
      if (isPlaying && audioContextRef.current && startTimeRef.current > 0) {
        const elapsed = audioContextRef.current.currentTime - startTimeRef.current;
        setCurrentTime(Math.min(elapsed, duration));
        
        if (elapsed < duration || isLoop) {
          requestAnimationFrame(updateTime);
        }
      }
    };
    requestAnimationFrame(updateTime);
  };

  const handleVolumeChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const newVolume = parseFloat(e.target.value);
    setVolume(newVolume);
  };

  const handleLoopToggle = () => {
    const newLoopState = !isLoop;
    console.log('🔄 切换循环状态:', isLoop, '->', newLoopState);
    setIsLoop(newLoopState);
    
    // 如果音频正在播放，需要重新创建源节点
    if (isPlaying && sourceNodeRef.current) {
      console.log('🔍 音频正在播放，重新创建源节点以更新循环状态');
      const wasPlaying = isPlaying;
      sourceNodeRef.current.stop();
      sourceNodeRef.current.disconnect();
      sourceNodeRef.current = null;
      setIsPlaying(false);
      
      // 重新播放
      setTimeout(() => {
        if (wasPlaying) {
          togglePlay();
        }
      }, 10);
    }
  };

  const formatTime = (time: number) => {
    const minutes = Math.floor(time / 60);
    const seconds = Math.floor(time % 60);
    return `${minutes}:${seconds.toString().padStart(2, '0')}`;
  };

  return (
    <div style={{ padding: '20px', maxWidth: '400px', margin: '0 auto' }}>
      <h2>Web Audio API 播放器</h2>
      
      {/* 播放控制区域 */}
      <div style={{ marginBottom: '20px' }}>
        <button
          onClick={togglePlay}
          style={{
            padding: '10px 20px',
            fontSize: '16px',
            backgroundColor: isPlaying ? '#ff4444' : '#4CAF50',
            color: 'white',
            border: 'none',
            borderRadius: '5px',
            cursor: 'pointer',
            marginRight: '10px'
          }}
        >
          {isPlaying ? '停止' : '播放'}
        </button>
        <button
          onClick={() => {
            console.log('🔍 手动检查音频状态:');
            console.log('  - 播放状态:', isPlaying);
            console.log('  - 循环状态:', isLoop);
            console.log('  - AudioContext状态:', audioContextRef.current?.state);
            console.log('  - 音频时长:', duration.toFixed(2) + 's');
            console.log('  - 当前播放时间:', currentTime.toFixed(2) + 's');
            console.log('  - 音量:', volume);
            console.log('  - 源节点:', sourceNodeRef.current);
            console.log('  - 增益节点:', gainNodeRef.current);
            console.log('  - 音频缓冲区:', audioBufferRef.current);
            if (audioContextRef.current) {
              console.log('  - AudioContext当前时间:', audioContextRef.current.currentTime.toFixed(2) + 's');
              console.log('  - AudioContext采样率:', audioContextRef.current.sampleRate);
              console.log('  - AudioContext基础延迟:', audioContextRef.current.baseLatency);
            }
          }}
          style={{
            padding: '10px 20px',
            fontSize: '14px',
            backgroundColor: '#2196F3',
            color: 'white',
            border: 'none',
            borderRadius: '5px',
            cursor: 'pointer'
          }}
        >
          调试信息
        </button>
      </div>

      {/* 进度条 */}
      <div style={{ marginBottom: '20px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '5px' }}>
          <span style={{ fontSize: '12px' }}>{formatTime(currentTime)}</span>
          <span style={{ fontSize: '12px' }}>{formatTime(duration)}</span>
        </div>
        <div
          style={{
            width: '100%',
            height: '6px',
            backgroundColor: '#ddd',
            borderRadius: '3px',
            overflow: 'hidden'
          }}
        >
          <div
            style={{
              width: duration > 0 ? `${(currentTime / duration) * 100}%` : '0%',
              height: '100%',
              backgroundColor: '#4CAF50',
              transition: 'width 0.1s ease'
            }}
          />
        </div>
      </div>

      {/* 音量控制区域 */}
      <div style={{ marginBottom: '20px' }}>
        <label style={{ display: 'block', marginBottom: '10px' }}>
          音量: {Math.round(volume * 100)}%
        </label>
        <input
          type="range"
          min="0"
          max="1"
          step="0.1"
          value={volume}
          onChange={handleVolumeChange}
          style={{ width: '100%' }}
        />
      </div>

      {/* 循环播放控制区域 */}
      <div style={{ marginBottom: '20px' }}>
        <label style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
          <input
            type="checkbox"
            checked={isLoop}
            onChange={handleLoopToggle}
            style={{ transform: 'scale(1.2)' }}
          />
          <span>循环播放</span>
        </label>
      </div>

      {/* 状态显示区域 */}
      <div style={{ fontSize: '14px', color: '#666', padding: '10px', backgroundColor: '#f5f5f5', borderRadius: '5px' }}>
        <p>状态: {isPlaying ? '播放中' : '已停止'}</p>
        <p>音量: {Math.round(volume * 100)}%</p>
        <p>循环播放: {isLoop ? '开启' : '关闭'}</p>
        <p>设备: {(() => {
          const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent);
          if (isIOS) {
            const iosVersionMatch = navigator.userAgent.match(/OS (\d+)_(\d+)_?(\d+)?/);
            const iosVersion = iosVersionMatch ? `${iosVersionMatch[1]}.${iosVersionMatch[2]}${iosVersionMatch[3] ? '.' + iosVersionMatch[3] : ''}` : null;
            return `iOS ${iosVersion || '未知版本'}`;
          }
          return '非iOS';
        })()}</p>
        {audioContextRef.current && (
          <>
            <p>AudioContext状态: {audioContextRef.current.state}</p>
            <p>采样率: {audioContextRef.current.sampleRate}Hz</p>
            <p>基础延迟: {audioContextRef.current.baseLatency ? (audioContextRef.current.baseLatency * 1000).toFixed(2) + 'ms' : '未知'}</p>
            <p>音频时长: {duration ? duration.toFixed(2) + 's' : '未知'}</p>
            <p>当前时间: {currentTime.toFixed(2)}s</p>
            <p>进度: {duration > 0 ? Math.round((currentTime / duration) * 100) + '%' : '0%'}</p>
            <p>源节点: {sourceNodeRef.current ? '已创建' : '未创建'}</p>
            <p>增益节点: {gainNodeRef.current ? '已创建' : '未创建'}</p>
            <p>音频缓冲区: {audioBufferRef.current ? '已加载' : '未加载'}</p>
          </>
        )}
      </div>
    </div>
  );
});
